<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v21;

use app\api\controller\v2\Auth;
use app\common\cachemodel\AppQq;
use app\common\cachemodel\AppWeibo;
use app\common\cachemodel\MiniAppUser;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Wechat;
use app\common\cachemodel\ZlUserTemporaryTelRecord;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\Alidayu;
use app\common\lib\exception\ApiException;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\User;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Log;
use think\response\Json;
use XznsTools\cache\CacheManage;

/**个人信息修改接口
 * @title
 * @desc
 * @url
 * @version 2.5.0
 * Class Demo
 * @package app\api\controller\v2
 */
class Info extends Auth
{
    protected $msg;


    /**
     * 三方绑定
     * @return Json
     * @throws ApiException
     * @throws GuzzleException
     */
    public function bind_third()
    {
        $param = input('param.param');
        $param = $param ? json_decode($param, true) : [];
        $type = input('param.type/d');
        $this->msg = '';
        switch ($type)
        {
            case 1:
                $header = request()->header('app-type');
                if ($header == 'ios')
                {
                    $wechat_user = $param;
                } else
                {
                    $wechat_user = (new Wechat())->WechatInfo($param);
                }
                $res = $this->wechat($wechat_user);
                break;
            case  2:
                $res = $this->qq($param);
                break;
            case  3:
                $res = $this->weibo($param);
                break;
            default:
                return show(config('code.error'), '未知的账号');
                break;
        }
        if ($this->msg)
        {
            return show(config('code.error'), $this->msg);
        }
        return show(200, '绑定成功', ['nickname' => $res]);
    }

    /**
     * 微信登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws Exception
     */
    protected function wechat($wechat_user)
    {
        //检测用户是否已绑定
        $WechatModel = new Wechat();
        $user_wechat = $WechatModel->getWechatInfo($this->user['id'], 2);
        if ($user_wechat)
        {
            $this->msg = '您已绑定微信';
            return false;
        }
        //验证是否注册过
        $User = (new Wechat())->getWechatInfo($wechat_user['unionid']);
        if ($User)
        {
            $this->msg = '当前微信已被注册';
            return false;
        }
        try
        {
            $wechat_insert = [
                'uid' => $this->user['id'],
                'nickname' => $wechat_user['nickname'] ?? '匿名用户',
                'sex' => $wechat_user['sex'] ?? 2,
                'city' => $wechat_user['city'] ?? '',
                'province' => $wechat_user['province'] ?? '',
                'country' => $wechat_user['country'] ?? '',
                'headimgurl' => $wechat_user['headimgurl'] ?? '',
                'openid' => $wechat_user['openid'],
                'unionid' => $wechat_user['unionid'],
                'create_time' => time(),
                'update_time' => time(),
            ];
            //qq表生成数据
            $WechatModel->SaveData($wechat_insert);

            // 小程序绑定
            $miniUsers = (new MiniAppUser())->where(['unionid' => $wechat_user['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->column('id');
            if ($miniUsers)
            {
                // 更新数据库状态
                (new MiniAppUser())->where(['unionid' => $wechat_user['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->update(['uid' => $this->user['id']]);
                // 删除缓存
                foreach ($miniUsers as $mid)
                {
                    CacheManage::getInstance()->setCacheConfig('miniapp.user', $mid)->rmCache();
                }
            }

            return $wechat_user['nickname'];
        }
        catch (\Exception $e)
        {
            $this->msg = '微信绑定失败';
        }
        return false;
    }

    /**
     * QQ登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    protected function qq($param)
    {
        //检测用户是否已绑定
        $QqModel = new AppQq();
        $user_qq = $QqModel->getUserQqInfoFromCache($this->user['id'], 2);
        if ($user_qq)
        {
            return $this->msg = '您已绑定qq';
        }
        // 获取用户qq信息
        $qq_user = $QqModel->QqInfo($param);
        // 验证是否注册过
        $User = (new AppQq())->getUserQqInfoFromCache($qq_user['unionid']);
        if ($User)
        {
            $this->msg = '当前qq号已被注册';
            return false;
        }
        try
        {
            $qq_insert = [
                'uid' => $this->user['id'],
                'openid' => $param['openid'],
                'unionid' => $qq_user['unionid'],
                'create_time' => time(),
                'nickname' => $qq_user['nickname'],
                'sex' => $qq_user['sex'],
                'avatar' => $qq_user['figureurl_qq_1'],
            ];
            //qq表生成数据
            (new AppQq())->SaveData($qq_insert);
            return $qq_user['nickname'];
        }
        catch (\Exception $e)
        {
            $this->msg = 'qq绑定失败';
        }
        return false;
    }

    /**
     * 微博登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    protected function weibo($param)
    {
        $WbModel = new AppWeibo();
        //检测用户是否已绑定微博
        $user_wb = $WbModel->getUserWbInfoFromCache($this->user['id'], 2);
        if ($user_wb)
        {
            $this->msg = '您已绑定微博';
            return false;
        }
        // 获取weibo信息
        $wb_user = $WbModel->WeiboInfo($param);
        // 验证当前微博是否注册过
        $User = (new AppWeibo())->getUserWbInfoFromCache($param['uid']);
        if ($User)
        {
            $this->msg = '当前微博已被注册';
            return false;
        }
        try
        {
            $wb_insert = [
                'uid' => $this->user['id'],
                'wbuid' => $param['uid'],
                'create_time' => time(),
                'nickname' => $wb_user['name'],
                'sex' => $wb_user['sex'],
                'avatar' => $wb_user['profile_image_url'],
            ];
            //wb表生成数据
            (new AppWeibo())->SaveData($wb_insert);
            return $wb_user['name'];
        }
        catch (\Exception $e)
        {
            $this->msg = '微博绑定失败';
        }
        return false;
    }

    /**
     * 个人中心绑定手机号
     * @return Json
     * @throws ApiException
     */
    public function bind_tel()
    {
        //检测用户是否已绑定
        if ($this->user['tel'])
        {
            return show(config('code.error'), '您已绑定手机号');
        }

        $tel = input('param.tel/s', '');
        $code = input('param.code/d', 0);
        $areaCode = input('param.area_code/d', 86);
        $mandatory = input('mandatory/d', 0);
        $mobileTel = $areaCode === 86 ? $tel : $areaCode . '-' . $tel;


        $appConfig = config('app');
        // 短信登录时，检测验证码是否正确
        if (!empty($code))
        {
            if (!in_array($tel, $appConfig['mobile'], false)
                || ($areaCode === 86 && $code != substr($appConfig['code'] * (substr($tel, 3, 6)), 0, 6)))
            {
                //苹果和安卓应用商店审核账号，固定验证码为666666
                if (($tel == '13045794520' && $code == '666666')
                    || ($tel == '13261877781' && $code == '666666'))
                {

                } else
                {
                    //  validate 严格校验
                    $mobileCode = Alidayu::getInstance()->checkSmsIdentify($tel, $areaCode);

                    if ($code != $mobileCode)
                    {
                        return show(config('code.error'), '短信验证码错误');
                    }
                }
            }
        } else
        {
            return show(config('code.error'), '请输入验证码');
        }

        $user = Util::CheckUserTel($tel, $areaCode);

        if (!$mandatory && $user && !empty($user))
        {
            return show(config('code.success'), '该手机号已被占用', [
                'type' => 2,
                'tel_user_name' => $user['nickname']
            ]);
        }
        if (!$tel || !$code || strlen($code) != 6)
        {
            return show(config('code.error'), '验证码错误');
        }
        // 若未注册
        try
        {
            // 开始绑定手机号
            if ($mandatory)
            {   // 绑定临时手机号身份凭证
                $bindInfo = [
                    'temporary_tel' => $mobileTel, // 国内手机号不拼接国际手机区号,
                    'tel_bind_time' => $this->request->time()
                ];
            } else
            {
                $bindInfo = ['tel' => $mobileTel, 'temporary_tel' => '', 'tel_bind_time' => 0];
            }
            (new User())->updateUserinfo(['id' => $this->user['id']], $bindInfo);
            (new ZlUserVip())->updateStarNum((int)$this->user['id'], 13); // 绑定手机号任务
            if ($mandatory)
            {   // 记录绑定临时手机号 记录
                (new ZlUserTemporaryTelRecord())->save([
                    'uid' => $this->user['id'],
                    'tel' => $mobileTel,
                    'create_time' => $this->request->time()
                ]);
            }
        }
        catch (\Exception $e)
        {
            Log::write($this->user['id'] . '绑定手机号失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return show(0, '绑定失败');
        }

        $distinctId = $this->request->header('distinct-id', '');
        if ($distinctId)
        {
            //  神策打点 用户绑定手机号时，设置用户属性
            SensorsData::profile($this->user['id'], true, ['user_phone_num' => $mobileTel], 'set');
        }

        return show(config('code.success'), '绑定成功', [
            'type' => 1,
        ]);
    }

    /**
     * 修改现居地
     */
    public function updateLiveAddress()
    {
        $liveCountry = input('live_country/s', '');
        $liveProvince = input('live_province/s', '');
        $liveCity = input('live_city/s', '');

        if (!$liveCity || !$liveCountry || !$liveProvince)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        $RecodeModel = new Recode();

        // 更新档案
        $res = $RecodeModel->UpdateData($this->user['id'], $this->user['rid'], [
            'live_country' => $liveCountry,
            'live_province' => $liveProvince,
            'live_city' => $liveCity,
        ]);
        if ($res)
        {
            return show(config('code.success'), '更新成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
